package com.yatb.trac.controller;

import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.transform.ResultTransformer;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.yatb.trac.pojo.Progetti;
import com.yatb.trac.pojo.StoricoTicket;
import com.yatb.trac.pojo.comparator.OrderBy;
import com.yatb.trac.pojo.comparator.StoricoTicketOrderByDataModifica;
import com.yatb.trac.pojo.transformer.ConsuntivoTicketTransformer;
import com.yatb.trac.service.SearchService;
import com.yatb.trac.util.SQLCondition;

public class DettaglioInterventoController extends AbstractController {

	private SearchService searchService ;
	private Properties sqlProperties;

	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String idTicket = request.getParameter("idTicket");
		String idProgetto = request.getParameter("idProgetto");
		Progetti p = searchService.findProgettoById(idProgetto);
		SQLCondition sqlCondition = new FindStoricoByIdTicket(idTicket);
		StoricoTicket[] st = searchService.find(new StoricoTicket[0], sqlCondition, StoricoTicket.class);
		Arrays.sort(st, new StoricoTicketOrderByDataModifica(OrderBy.DESC));
		String sql = getSqlProperties().getProperty("sql.consuntivo.byIdTicket");
		sql = MessageFormat.format(sql, idTicket);
		
		ResultTransformer resultTransformer = new ConsuntivoTicketTransformer();
		BigDecimal[][] result = searchService.find(new BigDecimal[0][0], sql, resultTransformer, null);
		
		
		
		ModelAndView mav = new ModelAndView("dettaglioIntervento");
		mav.getModel().put("storicoTickets", st);
		mav.getModel().put("descrizioneProgetto", p.getDescrizione());
		mav.getModel().put("orePreviste", result[0][0]);
		mav.getModel().put("oreConsuntivo", result[0][1]);
		return mav;
	}
	public SearchService getSearchService() {
		return searchService;
	}
	public void setSearchService(SearchService searchService) {
		this.searchService = searchService;
	}
	public Properties getSqlProperties() {
		return sqlProperties;
	}
	public void setSqlProperties(Properties sqlProperties) {
		this.sqlProperties = sqlProperties;
	}

}
